from flask import Blueprint, request, jsonify, send_file
import openai
import os
import tempfile
import base64
import io
from datetime import datetime

speech_bp = Blueprint('speech', __name__)

@speech_bp.route('/tts', methods=['POST'])
def text_to_speech():
    """文本转语音服务"""
    try:
        data = request.get_json()
        text = data.get('text')
        voice = data.get('voice', 'alloy')  # alloy, echo, fable, onyx, nova, shimmer
        
        if not text:
            return jsonify({'success': False, 'error': 'Text is required'}), 400
        
        # 使用OpenAI TTS API
        client = openai.OpenAI()
        
        response = client.audio.speech.create(
            model="tts-1",
            voice=voice,
            input=text,
            response_format="mp3"
        )
        
        # 创建临时文件
        temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.mp3')
        temp_file.write(response.content)
        temp_file.close()
        
        # 将音频文件转换为base64
        with open(temp_file.name, 'rb') as f:
            audio_data = base64.b64encode(f.read()).decode('utf-8')
        
        # 清理临时文件
        os.unlink(temp_file.name)
        
        return jsonify({
            'success': True,
            'data': {
                'audio_data': audio_data,
                'format': 'mp3',
                'text': text
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@speech_bp.route('/asr', methods=['POST'])
def speech_to_text():
    """语音转文本服务"""
    try:
        data = request.get_json()
        audio_data = data.get('audio_data')  # base64 encoded audio
        
        if not audio_data:
            return jsonify({'success': False, 'error': 'Audio data is required'}), 400
        
        # 解码base64音频数据
        audio_bytes = base64.b64decode(audio_data)
        
        # 创建临时文件
        temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.wav')
        temp_file.write(audio_bytes)
        temp_file.close()
        
        # 使用OpenAI Whisper API
        client = openai.OpenAI()
        
        with open(temp_file.name, 'rb') as audio_file:
            transcript = client.audio.transcriptions.create(
                model="whisper-1",
                file=audio_file,
                response_format="text"
            )
        
        # 清理临时文件
        os.unlink(temp_file.name)
        
        return jsonify({
            'success': True,
            'data': {
                'text': transcript,
                'confidence': 0.95  # 模拟置信度
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@speech_bp.route('/pronunciation-score', methods=['POST'])
def pronunciation_score():
    """发音评分服务"""
    try:
        data = request.get_json()
        reference_text = data.get('reference_text')
        audio_data = data.get('audio_data')
        
        if not all([reference_text, audio_data]):
            return jsonify({'success': False, 'error': 'Reference text and audio data are required'}), 400
        
        # 首先进行语音识别
        audio_bytes = base64.b64decode(audio_data)
        temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.wav')
        temp_file.write(audio_bytes)
        temp_file.close()
        
        client = openai.OpenAI()
        
        with open(temp_file.name, 'rb') as audio_file:
            recognized_text = client.audio.transcriptions.create(
                model="whisper-1",
                file=audio_file,
                response_format="text"
            )
        
        os.unlink(temp_file.name)
        
        # 简单的发音评分算法
        score = calculate_pronunciation_score(reference_text.lower(), recognized_text.lower())
        
        # 生成详细反馈
        feedback = generate_pronunciation_feedback(score, reference_text, recognized_text)
        
        return jsonify({
            'success': True,
            'data': {
                'overall_score': score,
                'reference_text': reference_text,
                'recognized_text': recognized_text,
                'accuracy': feedback['accuracy'],
                'fluency': feedback['fluency'],
                'pronunciation': feedback['pronunciation'],
                'feedback_text': feedback['text']
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

def calculate_pronunciation_score(reference, recognized):
    """计算发音分数"""
    # 简单的相似度计算
    from difflib import SequenceMatcher
    
    similarity = SequenceMatcher(None, reference, recognized).ratio()
    score = int(similarity * 100)
    
    # 确保分数在合理范围内
    return max(60, min(100, score))

def generate_pronunciation_feedback(score, reference, recognized):
    """生成发音反馈"""
    if score >= 90:
        accuracy = "Excellent"
        fluency = "Very Good"
        pronunciation = "Excellent"
        text = "Outstanding pronunciation! Keep up the great work!"
    elif score >= 80:
        accuracy = "Good"
        fluency = "Good"
        pronunciation = "Good"
        text = "Good pronunciation! Try to focus on clarity."
    elif score >= 70:
        accuracy = "Fair"
        fluency = "Fair"
        pronunciation = "Fair"
        text = "Fair pronunciation. Practice more to improve clarity."
    else:
        accuracy = "Needs Improvement"
        fluency = "Needs Improvement"
        pronunciation = "Needs Improvement"
        text = "Keep practicing! Focus on pronouncing each word clearly."
    
    return {
        'accuracy': accuracy,
        'fluency': fluency,
        'pronunciation': pronunciation,
        'text': text
    }

@speech_bp.route('/word-audio/<int:word_id>', methods=['GET'])
def get_word_audio(word_id):
    """获取单词音频"""
    try:
        from src.models.models import Word
        
        word = Word.query.get_or_404(word_id)
        
        # 如果已有音频URL，直接返回
        if word.audio_url:
            return jsonify({
                'success': True,
                'data': {
                    'audio_url': word.audio_url,
                    'word': word.en
                }
            })
        
        # 否则生成TTS音频
        client = openai.OpenAI()
        
        response = client.audio.speech.create(
            model="tts-1",
            voice="alloy",
            input=word.en,
            response_format="mp3"
        )
        
        # 创建临时文件并转换为base64
        temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.mp3')
        temp_file.write(response.content)
        temp_file.close()
        
        with open(temp_file.name, 'rb') as f:
            audio_data = base64.b64encode(f.read()).decode('utf-8')
        
        os.unlink(temp_file.name)
        
        return jsonify({
            'success': True,
            'data': {
                'audio_data': audio_data,
                'format': 'mp3',
                'word': word.en
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

